package com.jrx.anytxn.transaction.job.cmpsCrt.config;

import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.AnytxnBatchProperties;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.TlPaymentLog;
import com.jrx.anytxn.transaction.job.cmpsCrt.step.GuaranteeProcessor;
import com.jrx.anytxn.transaction.job.cmpsCrt.step.GuaranteeWriter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 代偿回购扣款
 */
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
public class GuaranteeConfiguration {

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private GuaranteeProcessor guaranteeProcessor;
    @Autowired
    private GuaranteeWriter guaranteeWriter;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Bean
    public Job guaranteeJob(){
        return jobBuilderFactory.get("guaranteeJob")
                .start(guaranteeStep())
                .build();
    }

    @Bean
    public Step guaranteeStep(){
        return stepBuilderFactory.get("guaranteeStep")
                .<TlPaymentLog,TlPaymentLog>chunk(anytxnBatchProperties.getGuaranteeJobConfig().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(guaranteeReader())
                .processor(guaranteeProcessor)
                .writer(guaranteeWriter)
                .transactionManager(platformTransactionManager)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getGuaranteeJobConfig().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<TlPaymentLog> guaranteeReader() {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        Date businessDate = org.getNextProcessingDate();

        MyBatisCursorItemReader<TlPaymentLog> paymentLogMyBatisCursorItemReader = new MyBatisCursorItemReader<>();
        paymentLogMyBatisCursorItemReader.setSaveState(false);
        paymentLogMyBatisCursorItemReader.setSqlSessionFactory(sqlSessionFactory);

        paymentLogMyBatisCursorItemReader.setQueryId("com.jrx.anytxn.transaction.mapper.ext.ExtTlPaymentLogMapper" +
                ".selectBySumStatusAndPaymentTypForBatch");
        Map<String,Object> map = new HashMap<>();

        map.put("sumStatus", TransBizConstant.PAYMENT_LOG_SUM_STATUS_D);
        map.put("businessDate", businessDate);
        map.put("paymentTypeList", Arrays.asList(TransBizConstant.REPAYMENT_TYPE_CMPS,TransBizConstant.REPAYMENT_TYPE_CRT));
        paymentLogMyBatisCursorItemReader.setParameterValues(map);

        SynchronizedItemStreamReader<TlPaymentLog> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(paymentLogMyBatisCursorItemReader);
        return synchronizedItemStreamReader;
    }
}
